<template>
  <div class="p-6 min-h-screen">
    <a-skeleton :loading="loading" active>
      <div class="shadow-md rounded-md p-6 flex flex-col" v-if="!loading">
        <div
          class="text-2xl text-gray-700 border-b pb-2 mb-4 flex justify-between"
        >
          <div>
            <span class="text-green-500 font-bold mr-2">|</span>班级详情
          </div>
          <div class="flex gap-4">
            <a-button type="primary" ghost @click="goToClassPage"
              >返回</a-button
            >
            <a-button type="primary" @click="goToRollCall">去点名</a-button>
          </div>
        </div>

        <div v-if="classData" class="mt-4 flex flex-col">
          <div class="flex justify-between items-center">
            <div>
              <p class="text-lg font-medium text-gray-600">
                班级名称:
                <span class="text-gray-800">{{ classData.class_name }}</span>
              </p>
              <p class="text-lg font-medium text-gray-600">
                年级:
                <span class="text-gray-800">{{
                  mapLevelToCNName(classData.grade)
                }}</span>
              </p>
              <p class="text-lg font-medium text-gray-600">
                学生人数:
                <span class="text-gray-800">{{ students.length }}</span>
              </p>
            </div>
            <div class="flex space-x-4">
              <a-button type="primary" @click="showAddStudentModal"
                >新增学生</a-button
              >
              <a-button type="default" @click="showImportModal"
                >批量导入</a-button
              >
            </div>
          </div>
          <div class="flex-1">
            <a-table
              :columns="columns"
              :data-source="students"
              row-key="stu_no"
              class="mt-6 bg-white shadow-sm rounded-md"
              :pagination="pagination"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'operation'">
                  <a-button
                    type="primary"
                    size="small"
                    @click="openEditStudentModal(record)"
                    class="mr-2"
                    >编辑</a-button
                  >
                  <a-popconfirm
                    title="确定删除该学生吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="confirmDeleteStudent(record.stu_no)"
                  >
                    <a-button type="danger" size="small">删除</a-button>
                  </a-popconfirm>
                </template>
              </template>
            </a-table>
          </div>
        </div>
        <div v-else>
          <p class="text-center text-red-500">无法加载班级信息，请稍后再试。</p>
        </div>
      </div>
    </a-skeleton>

    <a-modal
      v-model:visible="addStudentModalVisible"
      title="新增学生"
      ok-text="确认"
      cancel-text="取消"
      @ok="addStudent"
    >
      <a-form :model="newStudent" layout="vertical">
        <a-form-item
          label="学号"
          :rules="[{ required: true, message: '请输入学号' }]"
        >
          <a-input v-model:value="newStudent.stu_no" />
        </a-form-item>
        <a-form-item
          label="学生姓名"
          :rules="[{ required: true, message: '请输入学生姓名' }]"
        >
          <a-input v-model:value="newStudent.stu_name" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="editStudentModalVisible"
      title="编辑学生"
      ok-text="确认"
      cancel-text="取消"
      @ok="updateStudent"
    >
      <a-form :model="editingStudent" layout="vertical">
        <a-form-item
          label="学生姓名"
          :rules="[{ required: true, message: '请输入学生姓名' }]"
        >
          <a-input v-model:value="editingStudent.stu_name" />
        </a-form-item>
        <a-form-item
          label="积分"
          v-if="userStore.isLoggedIn"
          :rules="[{ required: true, message: '请输入积分' }]"
         
        >
          <a-input-number v-model:value="editingStudent.points" />
          
        </a-form-item>
        <a-form-item v-else label="积分">
          <p class="text-red-500">登录后可修改积分</p>
          <a-input-number
            v-model:value="editingStudent.points"
            disabled
            placeholder="登录后才能修改积分"
          />
          
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="importModalVisible"
      title="批量导入学生"
      ok-text="导入"
      cancel-text="取消"
      @ok="importStudents"
      width="600px"
    >
      <a-tabs v-model:activeKey="importTab">
        <a-tab-pane key="paste" tab="粘贴表格数据">
          <a-form layout="vertical" class="mt-4">
            <a-form-item label="粘贴学生数据（学号 姓名）">
              <a-textarea
                v-model:value="pastedData"
                placeholder="例如：
  101 张三
  102 李四"
                rows="6"
              ></a-textarea>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="upload" tab="上传 Excel 文件">
          <div class="mt-4">
            <a-upload
              accept=".xls,.xlsx"
              :before-upload="beforeFileUpload"
              :show-upload-list="false"
            >
              <a-button><FileAddOutlined />选择文件</a-button>
            </a-upload>
            <a-button class="ml-2" @click="downloadTemplate">
              <DownloadOutlined />
              下载模板
            </a-button>
            <span v-if="uploadedFileName" class="ml-2">{{
              uploadedFileName
            }}</span>
          </div>
          <div class="mt-4">
            <p>示例</p>
            <a-table
              :columns="sampleColumns"
              :data-source="sampleData"
              pagination="false"
              bordered
              size="small"
            ></a-table>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { mapLevelToCNName } from "@/utils/mapLevel";
import * as XLSX from "xlsx";
import { message, Modal } from "ant-design-vue";
import router from "@/router";
import { useClassStore } from "@/stores/class";
import { DownloadOutlined, FileAddOutlined } from "@ant-design/icons-vue";
import { useUserStore } from "@/stores/user";
const route = useRoute();
const classNo = route.params.classNo;
const className = route.params.className;
const classStore = useClassStore();
const userStore = useUserStore();

const classData = ref(null);
const loading = ref(true);
const students = ref([]);
const columns = [
  { title: "学号", dataIndex: "stu_no", key: "stu_no" },
  { title: "姓名", dataIndex: "stu_name", key: "stu_name" },
  { title: "积分", dataIndex: "points", key: "points" },
  { title: "答问次数", dataIndex: "attempts", key: "attempts" },
  { title: "正确次数", dataIndex: "corrects", key: "corrects" },
  {
    title: "正确率",
    dataIndex: "accuracy",
    key: "accuracy",
    customRender: ({ record }) => {
      const accuracy =
        record.attempts > 0
          ? ((record.corrects / record.attempts) * 100).toFixed(2) + "%"
          : "0.00%";
      return accuracy;
    },
  },
  {
    title: "操作",
    dataIndex: "operation",
    key: "operation",
    align: "center",
    fixed: "right",
    width: 150,
  },
];

const sampleColumns = [
  { title: "学号", dataIndex: "stu_no", key: "stu_no" },
  { title: "姓名", dataIndex: "stu_name", key: "stu_name" },
];
const sampleData = [
  { stu_no: "101", stu_name: "张三" },
  { stu_no: "102", stu_name: "李四" },
];
const downloadTemplate = async () => {
  const result = await window.electronAPI.saveFile();
  if (result.success) {
    message.success(`文件已保存到：${result.path}`);
  } else {
  }
};
const currentPage = ref(1);
const pageSize = ref(5);
const pagination = computed(() => ({
  current: currentPage.value,
  total: students.value.length,
  pageSize: pageSize.value,
  pageSizeOptions: [],
  showSizeChanger: true,
  showQuickJumper: true,
  onChange: (page, size) => {
    currentPage.value = page;
    pageSize.value = size;
  },
}));
const addStudentModalVisible = ref(false);
const importModalVisible = ref(false);
const editStudentModalVisible = ref(false);
const newStudent = ref({ stu_no: "", stu_name: "" });
const editingStudent = ref({ stu_no: "", stu_name: "", points: 0 });

let importedFile = null;
const pastedData = ref("");
const importTab = ref("paste");
const uploadedFileName = ref("");
const goToClassPage = () => {
  router.go(-1);
};
const goToRollCall = () => {
  const currentClass = {
    class_no: classNo,
    class_name: className,
  };
  classStore.selectClass(currentClass);
  router.push("/roll-call");
};
const loadClassData = async () => {
  try {
    const response = await window.electronAPI.getClassDataByNo(classNo);
    if (response.success) {
      classData.value = response.class;
      students.value = response.students || [];
    } else {
      classData.value = null;
    }
  } catch (error) {
    console.error("加载班级数据出错", error);
    classData.value = null;
  } finally {
    loading.value = false;
  }
};
const showAddStudentModal = () => {
  newStudent.value = { stu_no: "", stu_name: "" };
  addStudentModalVisible.value = true;
};
const showImportModal = () => {
  importModalVisible.value = true;
};
const addStudent = async () => {
  if (newStudent.value.stu_no && newStudent.value.stu_name) {
    const saveData = {
      class_no: classNo,
      stu_no: newStudent.value.stu_no,
      stu_name: newStudent.value.stu_name,
      points: 0,
      attempts: 0,
      corrects: 0,
    };
    const response = await window.electronAPI.saveStudentData([saveData]);
    if (response.success) {
      await loadClassData();
      addStudentModalVisible.value = false;
      message.success("新增学生成功！");
    } else {
      message.error(`新增学生失败: ${response.message || response.error}`);
    }
  }
};
const openEditStudentModal = (student) => {
  editingStudent.value = { ...student };
  editStudentModalVisible.value = true;
};
const updateStudent = async () => {
  

  if (editingStudent.value.stu_no && editingStudent.value.stu_name) {
    const newStudentData = {
      stu_no: editingStudent.value.stu_no,
      stu_name: editingStudent.value.stu_name,
      points: userStore.isLoggedIn ? editingStudent.value.points : undefined,
    };

    const response = await window.electronAPI.updateStuData([newStudentData]);
    if (response.success) {
      await loadClassData();
      editStudentModalVisible.value = false;
      message.success("编辑学生成功！");
    } else {
      message.error(`编辑学生失败: ${response.error}`);
    }
  }
};

const confirmDeleteStudent = (stu_no) => {
  return deleteStudent(stu_no);
};
const deleteStudent = async (stu_no) => {
  const response = await window.electronAPI.deleteStuData(stu_no);
  if (response.success) {
    await loadClassData();
    message.success("删除学生成功！");
  } else {
    message.error(`删除学生失败: ${response.error}`);
  }
};
const importStudents = async () => {
  let studentsToImport = [];
  if (importTab.value === "paste") {
    if (!pastedData.value.trim()) {
      message.error("请粘贴有效的学生数据！");
      return;
    }
    const lines = pastedData.value.trim().split("\n");
    for (let line of lines) {
      const parts = line.trim().split(/\s+/);
      if (parts.length < 2) {
        message.error(`数据格式错误: "${line}"`);
        return;
      }
      const [stu_no, stu_name] = parts;
      studentsToImport.push({
        class_no: classNo,
        stu_no: stu_no,
        stu_name: stu_name,
        points: 0,
        attempts: 0,
        corrects: 0,
      });
    }
  } else if (importTab.value === "upload") {
    if (!importedFile) {
      message.error("请上传有效的 Excel 文件！");
      return;
    }
    const reader = new FileReader();
    reader.onload = async (e) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: "array" });
      const sheet = workbook.Sheets[workbook.SheetNames[0]];
      const jsonData = XLSX.utils.sheet_to_json(sheet, {
        header: 1,
        defval: "",
        range: 1,
      });
      jsonData.forEach((row) => {
        const [stu_no, stu_name] = row;
        if (!stu_no || !stu_name) return;
        studentsToImport.push({
          class_no: classNo,
          stu_no: String(stu_no).trim(),
          stu_name: String(stu_name).trim(),
          points: 0,
          attempts: 0,
          corrects: 0,
        });
      });
      if (studentsToImport.length === 0) {
        message.error("没有有效的学生数据！");
        return;
      }
      const response = await window.electronAPI.saveStudentData(
        studentsToImport
      );
      if (response.success) {
        await loadClassData();
        importModalVisible.value = false;
        message.success("批量导入学生成功！");
        uploadedFileName.value = "";
        importedFile = null;
      } else {
        message.error(`导入学生失败: ${response.message || response.error}`);
      }
    };
    reader.readAsArrayBuffer(importedFile);
    return;
  }
  if (studentsToImport.length === 0) {
    message.error("没有有效的学生数据！");
    return;
  }
  const response = await window.electronAPI.saveStudentData(studentsToImport);
  if (response.success) {
    await loadClassData();
    importModalVisible.value = false;
    message.success("批量导入学生成功！");
    pastedData.value = "";
  } else {
    message.error(`导入学生失败: ${response.message || response.error}`);
  }
};
const handleFileUpload = (file) => {
  importedFile = file;
  uploadedFileName.value = file.name;
};
const beforeFileUpload = (file) => {
  handleFileUpload(file);
  return false;
};
onMounted(() => {
  loadClassData();
});
</script>
<style scoped lang="less">
::v-deep .ant-select-selector {
  min-width: 100px;
}
</style>
